package cn.wolfcode.web.controller;

import cn.wolfcode.domain.Department;
import cn.wolfcode.domain.Employee;
import cn.wolfcode.domain.Role;
import cn.wolfcode.qo.EmployeeQueryObject;
import cn.wolfcode.qo.JsonResult;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IDepartmentService;
import cn.wolfcode.service.IEmployeeService;
import cn.wolfcode.service.IRoleService;
import com.alibaba.excel.EasyExcel;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;

@Controller
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private IEmployeeService employeeService;

    @Autowired
    private IDepartmentService departmentService;

    @Autowired
    private IRoleService roleService;


    // 处理查询所有员工请求
    @RequestMapping("/list")
    public String list(Model model, @ModelAttribute("qo")EmployeeQueryObject qo){

        //获取subject中的身份信息（realm return的身份信息是什么）
        //Object principal = SecurityUtils.getSubject().getPrincipal();

        model.addAttribute("pageInfo", employeeService.query(qo));

        List<Department> departments = departmentService.listAll();
        model.addAttribute("departments", departments);

        return "employee/list"; // 找视图 /WEB-INF/views/employee/list.jsp
    }

    // 去新增或去修改
    @RequestMapping("/input")
    public String input(Long id, Model model){
        List<Department> departments = departmentService.listAll();
        model.addAttribute("departments", departments);

        //查询所有角色
        List<Role> roles = roleService.listAll();
        model.addAttribute("roles",roles);

        if (id != null) { // 表示去修改
            Employee employee = employeeService.get(id);
            model.addAttribute("employee", employee);
        }
        return "employee/input"; // 让重新发一次请求
    }

    @RequestMapping("/delete")
    public String delete(Long id){
        if (id != null) {
            employeeService.delete(id);
        }
        return "redirect:/employee/list.do"; // 让重新发一次请求
    }


    // 新增或修改
    @RequestMapping("/saveOrUpdate") // dept.id 2
    @ResponseBody
    public JsonResult saveOrUpdate(Employee employee,Long[] ids){
       try {
           if(employee.getId()  == null){ // 新增
               employeeService.save(employee,ids);
           }else {
               employeeService.update(employee,ids); // 修改
           }
           return new JsonResult();
       }catch (Exception e){
           e.printStackTrace();
           return new JsonResult(false,"操作失败");
       }
    }

    @RequestMapping("/batchDelete")
    @ResponseBody
    public JsonResult batchDelete(/*@RequestParam("ids[]")*/ Long[] ids){
        try{
            employeeService.batchDelete(ids);
            return new JsonResult();
        }catch (Exception e){
            e.printStackTrace();
            return new JsonResult(false,"操作失败");
        }
    }

    /**
     * 插件要求返回valid:false（验证不通过） valid:true（验证通过）
     * @param name
     * @return
     */
    @RequestMapping("/checkName")
    @ResponseBody
    public HashMap checkName(String name){
        Employee employee = employeeService.selectByName(name);
        HashMap<Object, Object> map = new HashMap<>();
        map.put("valid",true);
        return map;
    }

    /**
     * 导出
     */
    @RequestMapping("/exportXls")
    public void exportXls(HttpServletResponse response) throws IOException {
        //文件下载的响应头（让浏览器访问资源的的时候以下载的方式打开）
        response.setHeader("Content-Disposition","attachment;filename=employee.xls");
        //调用service的导出方法
       /* Workbook workbook = employeeService.exportXls();
        //输出文件
        workbook.write(response.getOutputStream());*/

        //使用阿里EasyExcel
        List<Employee> employees = employeeService.listAll();
        EasyExcel.write(response.getOutputStream(), Employee.class)
                .sheet("员工通讯录").doWrite(employees);


    }

    /**
     * 导入
     */
    @RequestMapping("/importXls")
    @ResponseBody
    public JsonResult importXls(MultipartFile file) throws IOException {
        employeeService.importXls(file);
        //读上传过来的文件
        return new JsonResult();
    }
}
